/**
 * Actively Replicated Crash Free Single Software Failure (non Byzantine)
 * Distributed Retail Store 
 * 
 * November 25 2012
 */
package comp6231.project.frontend;

import java.math.BigInteger;

import comp6231.project.common.Message;
import comp6231.project.common.BinarySemaphore;

/**
 * Impose total ordering of request messages.
 * 
 * @author dimitri.tiago
 */
public class Sequencer {
	
	// TODO: validate that BigInteger data-type works for 64bit unsigned representation.
	private BigInteger totalOrderSequenceNumber;
	private BigInteger increment;
	
	private BinarySemaphore writer;

	/**
	 * Default no-argument constructor initializes instance varibles
	 */
	public Sequencer()
	{
		totalOrderSequenceNumber = BigInteger.valueOf(0);
		increment 				 = BigInteger.valueOf(1);
		
		writer 		 			 = new BinarySemaphore(true);
	}

	/**
	 * Assign monotonically increasing total order sequence number to incoming 
	 * request messages. 
	 * @param request <code>Message</code> object with client request data.
	 */
	public void setTotalOrder(Message request)
	{
		writer.Wait(); // enter CS
		
		// increment and set total order sequence number
		totalOrderSequenceNumber = totalOrderSequenceNumber.add(increment);
		request.sequenceNum		 = totalOrderSequenceNumber;
		
		writer.Signal(); // exit CS
	}
}
